import { AppContext } from "@/providers";
import {
	Button,
	Form,
	Modal,
	Table,
	TableColumnProps,
	Image,
	FormInstance,
	Input,
	InputNumber,
	Typography,
	Popconfirm,
	message,
	Tooltip,
} from "antd";
import { cloneDeep } from "lodash";
import {
	createRef,
	forwardRef,
	ForwardRefRenderFunction,
	HTMLAttributes,
	RefObject,
	useContext,
	useImperativeHandle,
	useMemo,
	useRef,
	useState,
} from "react";
// import { html } from "@codemirror/lang-html";
import qs from "qs";
import { SkuAttribute } from "@/typings/goods";
import ImgUpload from "@/components/dataEntry/ImgUpload";
import AddOptionModal from "./components/AddOptionModal";
import SkuFormList from "./components/SkuFormList/SkuFormList";
import EllipsisText from "@/components/dataPresentation/EllipsisText";
import { getSkuValue } from "./components/SkuFormList/components/SkuSelect";
import { OperateGoodsContext } from "../../OperateGoods";
import RichTextInput, { RichTextInputRef } from "@/components/dataEntry/RichTextInput";
import { StyledArrowRow, StyledDownOutlined, StyledUpOutlined } from "../../styled";

interface ValueListItem {
	image: string | null;
	name: string;
}
export interface AttributesItem {
	key: string;
	value: ValueListItem;
}
interface DataSourceItem {
	attributes: AttributesItem[];
	name: string;
	detail: string | null;
	price: number;
	originalPrice: number | null;
	stock: number;
	images: string[] | null;
}
export interface SkuFormListItem {
	key: string | null;
	value: string | null;
	ref: RefObject<FormInstance>;
}
const initialSkuFormList = [{ key: null, value: null, ref: createRef<FormInstance>() }];
export interface SkuTableRef {
	getData: () => DataSourceItem[];
	setData: (data: DataSourceItem[]) => void;
}
const SkuTable: ForwardRefRenderFunction<SkuTableRef> = (_, ref) => {
	const [dataSource, setDataSource] = useState<DataSourceItem[]>([]);
	useImperativeHandle(
		ref,
		() => ({
			getData: () => dataSource,
			setData: setDataSource,
		}),
		[dataSource]
	);
	const [skuFormList, setSkuFormList] = useState<SkuFormListItem[]>(cloneDeep(initialSkuFormList));
	const richTextInputRef = useRef<RichTextInputRef>(null);
	const generateOperateButton = (type: "clone" | "edit", index: number, className?: HTMLAttributes<HTMLDivElement>["className"]) => (
		<Button
			className={className}
			type={type === "edit" ? "primary" : "default"}
			size="small"
			onClick={() => {
				setFormOpen(true);
				setOperateType(type);
				const record = dataSource[index];
				operateIndex.current = index;
				const { attributes, price, originalPrice, detail, ...remainingRecord } = record;
				baseFormRef.current?.setFieldsValue({
					price: price / 100,
					originalPrice: originalPrice ? originalPrice / 100 : null,
					...remainingRecord,
				});
				richTextInputRef.current?.setValue(detail || "");
				setSkuFormList(
					attributes.length
						? attributes.map((item) => ({
								key: item.key,
								value: getSkuValue(item.value.name, item.value.image),
								ref: createRef(),
						  }))
						: cloneDeep(initialSkuFormList)
				);
			}}
		>
			{type === "edit" ? "编辑" : "克隆"}
		</Button>
	);
	const moveRecord = (index: number, position: -1 | 1) => {
		const copiedData = cloneDeep(dataSource);
		if (position === -1) {
			copiedData.splice(index - 1, 0, copiedData.splice(index, 1)[0]);
		} else {
			copiedData.splice(index, 0, copiedData.splice(index + 1, 1)[0]);
		}
		setDataSource(copiedData);
	};
	const columns = useMemo<TableColumnProps<DataSourceItem>[]>(
		() => [
			{
				dataIndex: "name",
				title: "sku名",
				width: 150,
				render: (text, _, index) => (
					<div>
						<StyledArrowRow>
							{index !== 0 && (
								<Tooltip title="向上移动">
									<StyledUpOutlined onClick={() => moveRecord(index, -1)} />
								</Tooltip>
							)}
						</StyledArrowRow>
						<EllipsisText>{text}</EllipsisText>
						<StyledArrowRow>
							{index !== dataSource.length - 1 && (
								<Tooltip title="向下移动" placement="bottom">
									<StyledDownOutlined onClick={() => moveRecord(index, 1)} />
								</Tooltip>
							)}
						</StyledArrowRow>
					</div>
				),
			},
			{
				dataIndex: "price",
				title: "价格",
				width: 100,
				render: (text) => (text ? `${text / 100}元` : "-"),
			},
			{
				dataIndex: "originalPrice",
				title: "原价",
				width: 100,
				render: (text) => (text ? `${text / 100}元` : "-"),
			},
			{
				dataIndex: "stock",
				title: "库存",
				width: 100,
			},
			{
				dataIndex: "attributes",
				title: "sku",
				width: 100,
				render: (list: SkuAttribute[]) => (
					<div>
						{list.map(({ key, value }, index) => {
							const { name, image } = value || {};
							return (
								<div key={index} className="mb-2 flex">
									<div>{key}：</div>
									<div className="flex">
										{image && (
											<Image
												height={20}
												width={20}
												style={{ objectFit: "cover" }}
												src={`${REACT_APP_BASEURL}${image}`}
											/>
										)}
										<div className="ml-2">{name}</div>
									</div>
								</div>
							);
						})}
					</div>
				),
			},
			{
				dataIndex: "images",
				title: "规格图片",
				ellipsis: true,
				width: 300,
				render: (list: string[]) => (
					<div className="flex overflow-x-scroll" style={{ width: "400px" }}>
						{list.map((item, index) => (
							<div key={index} className="mr-2">
								<Image width={30} height={30} style={{ objectFit: "cover" }} src={`${REACT_APP_BASEURL}${item}`} />
							</div>
						))}
					</div>
				),
			},
			{
				title: "操作",
				width: 130,
				fixed: "right",
				render: (_, _1, index) => (
					<>
						{generateOperateButton("edit", index)}
						{generateOperateButton("clone", index, "ml-2")}
						<Popconfirm
							title="确认删除该sku吗？"
							onConfirm={() => {
								const copiedData = cloneDeep(dataSource);
								copiedData.splice(index, 1);
								setDataSource(copiedData);
							}}
						>
							<Button size="small" className="ml-2" danger>
								删除
							</Button>
						</Popconfirm>
					</>
				),
			},
		],
		[dataSource]
	);
	const [formOpen, setFormOpen] = useState(false);
	const { REACT_APP_BASEURL } = useContext(AppContext);
	const { skuOptions } = useContext(OperateGoodsContext);
	const baseFormRef = useRef<FormInstance>(null);
	const [addOptionsOpen, setAddOptionsOpen] = useState(false);
	const [operateType, setOperateType] = useState<"add" | "edit" | "clone">("add");
	const operateIndex = useRef<number>();
	return (
		<div>
			<Table
				columns={columns}
				dataSource={dataSource.map((item, key) => ({ ...item, key }))}
				pagination={false}
				scroll={{ x: "1600px", y: "700px" }}
			/>
			<Button
				size="small"
				type="primary"
				shape="round"
				className="mt-2"
				onClick={() => {
					setFormOpen(true);
					setOperateType("add");
					baseFormRef.current?.resetFields();
					setSkuFormList(cloneDeep(initialSkuFormList));
				}}
			>
				添加sku
			</Button>
			<Modal
				width={900}
				title={`${operateType === "edit" ? "编辑" : operateType === "add" ? "添加" : "克隆"}sku`}
				open={formOpen}
				forceRender
				onCancel={() => setFormOpen(false)}
				onOk={async () => {
					const { price, originalPrice, ...baseFormData } = (await baseFormRef.current?.validateFields()) || {};
					const copiedData = cloneDeep(dataSource);
					const dataItem = {
						...baseFormData,
						price: price * 100,
						originalPrice: originalPrice * 100,
						attributes: skuFormList.map((item) => {
							item.ref.current?.validateFields();
							const { key, value } = item;
							const { name, image } = qs.parse(value || "{}");
							return {
								key,
								value: {
									name,
									image: image || null,
								},
							};
						}),
					};
					const someEmpty = dataItem.attributes.some((item: AttributesItem) => !item.key || !item.value.name);
					if (someEmpty) return;
					if (skuFormList.length !== skuOptions.length) return message.error("请添加所有规格");
					if (["add", "clone"].includes(operateType)) {
						copiedData.push(dataItem);
					}
					if (operateType === "edit") {
						if (operateIndex.current === undefined) return;
						copiedData[operateIndex.current] = dataItem;
					}
					setDataSource(copiedData);
					setFormOpen(false);
				}}
			>
				<Form ref={baseFormRef} labelCol={{ span: 3 }} wrapperCol={{ span: 19 }} initialValues={{ images: [] }}>
					<Form.Item label="sku名" name="name" rules={[{ required: true, message: "请输入sku名" }]} wrapperCol={{ span: 8 }}>
						<Input placeholder="请输入sku名" />
					</Form.Item>
					<Form.Item label="价格" name="price" rules={[{ required: true, message: "请输入价格" }]}>
						<InputNumber placeholder="请输入价格，单位：元" min={1} style={{ width: "200px" }} />
					</Form.Item>
					<Form.Item label="原价" name="originalPrice">
						<InputNumber placeholder="请输入原价，单位：元" min={1} style={{ width: "200px" }} />
					</Form.Item>
					<Form.Item label="库存" name="stock" rules={[{ required: true, message: "请输入库存" }]}>
						<InputNumber placeholder="请输入库存" min={1} style={{ width: "200px" }} />
					</Form.Item>
					<Form.Item label="规格详情" name="detail">
						<RichTextInput
							field="detail"
							formRef={baseFormRef}
							height={300}
							ref={richTextInputRef}
							placeholder="请输入商品详情（HTML）"
						/>
					</Form.Item>
					<Form.Item label="规格图片" name="images">
						<ImgUpload multiple field="images" formRef={baseFormRef} />
					</Form.Item>
				</Form>
				<Typography.Link className="whitespace-nowrap ml-28" onClick={() => setAddOptionsOpen(true)}>
					添加sku类型选项
				</Typography.Link>
				<AddOptionModal open={addOptionsOpen} setOpen={setAddOptionsOpen} />
				<SkuFormList skuFormList={skuFormList} setSkuFormList={setSkuFormList} />
			</Modal>
		</div>
	);
};

export default forwardRef(SkuTable);
